package com.helloworld.core.common.util.file;

import com.drew.imaging.ImageMetadataReader;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.Arrays;

/**
 * 读取文件的元数据信息
 * <a href="https://github.com/drewnoakes/metadata-extractor">源代码</a>
 */
public class FIleMetadataUtil {

    public static Metadata readMetadata(String path) throws Exception {
        if (path.startsWith("http://") || path.startsWith("https://")) {
            try (InputStream in = new URL(path).openStream()) {
                return ImageMetadataReader.readMetadata(in);
            }
        }
        File jpegFile = new File(path);
        return ImageMetadataReader.readMetadata(jpegFile);
    }

    public static void main(String[] args) throws Exception {
        Metadata yuanTu = readMetadata("https://luhu-static-test.crm.luxelakes.com//upload/2024/7/10/1720576243613.jpg"); // 苹果手机原图
        Metadata up = readMetadata("https://luhu-static-test.crm.luxelakes.com//upload/2024/7/10/1720576207464.jpg"); // 苹果手机拍照上传
        Metadata up2 = readMetadata("https://luhu-static-test.crm.luxelakes.com//upload/2024/7/10/1720576207464.jpg"); // 安卓原图上传
        Metadata snap = readMetadata("https://luhu-static-test.crm.luxelakes.com//upload/2024/7/10/1720579109239.jpg"); // 安卓截图上传
        Metadata y1 = readMetadata("/Users/helloworld/Pictures/WechatIMG8.jpg"); // 微信传文件
        Metadata y2 = readMetadata("/Users/helloworld/Pictures/IMG_20240710_103637.jpg"); // 真正原图

        for (Metadata metadata : Arrays.asList(yuanTu, up, up2, snap, y1)) {
            for (Directory directory : metadata.getDirectories()) {
                for (Tag tag : directory.getTags()) {
                    System.out.printf("【tagType】%s,【tagName】%s【directory】%s【Description】%s【toString】%s %n", tag.getTagType(), tag.getTagName(),
                            tag.getDirectoryName(), tag.getDescription(), tag);
                }
            }
            System.out.println("=======================");
        }

//        // obtain the Exif directory
//        ExifSubIFDDirectory directory = metadata.getFirstDirectoryOfType(ExifSubIFDDirectory.class);
//        // query the tag's value
//        Date date = directory.getDate(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL);
    }

}
